import axios from 'axios'
// import Qs from 'qs'
import router from '@/router/index'
import store from '@/store/index'
import { Notification } from 'element-ui' // Message,
import { Message } from 'element-ui';

const toLogin = () => {
  // router.push({
  //     path: '/login',
  //     query: {
  //         redirect: router.currentRoute.fullPath
  //     }
  // })
  store.dispatch('user/logout').then(() => {
    router.push({
      name: 'login'
    })
  })
}

const api = axios.create({
  baseURL: process.env.VUE_APP_API_ROOT,
  timeout: 2*60*1000, // 2分钟
  responseType: 'json'
  // withCredentials: true
})

// api.interceptors.request.use(
//     request => {
//         if (request.method == 'post') {
//             request.headers['client-type'] = store.state.user.client_type;
//             if (request.data instanceof FormData) {
//                 if (store.getters['user/isLogin']) {
//                     // 如果是 FormData 类型（上传图片）
//                     request.data.append('token', store.state.user.token);
//                 }
//             } else {
//                 // 带上 token
//                 if (request.data == undefined) {
//                     request.data = {};
//                 }
//                 if (store.getters['user/isLogin']) {
//                     // request.data.token = store.state.user.token
//                     request.headers['Authorization'] = 'Bearer ' + store.state.user.token;
//                 }
//                 // request.data = Qs.stringify(request.data)
//             }
//         } else {
//             // console.log(request, '<======= api.interceptors.request');
//             request.headers['client-type'] = store.state.user.client_type;
//             // 带上 token
//             if (request.params == undefined) {
//                 request.params = {};
//             }
//             if (store.getters['user/isLogin']) {
//                 request.headers['Authorization'] = 'Bearer ' + store.state.user.token;
//             }
//         }
//         return request
//     }
// )
api.interceptors.request.use(
  request => {
    if (request.method == 'post') {
      if (request.data instanceof FormData) {
        if (store.getters['user/isLogin']) {
          // 如果是 FormData 类型（上传图片）
          request.data.append('token', store.state.user.token)
        }
      } else {
        // 带上 token
        if (request.data == undefined) {
          request.data = {}
        }
        if (store.getters['user/isLogin']) {
          request.headers['Allocation'] = 'PC';
          request.headers['Authorization'] = 'Bearer ' + store.state.user.token;
        }
      }
    } else {
      // 带上 token
      if (request.params == undefined) {
        request.params = {}
      }
      if (store.getters['user/isLogin']) {
        request.headers['Allocation'] = 'PC';
        request.headers['Authorization'] = 'Bearer ' + store.state.user.token;
      }
    }
    return request
  }
)
api.interceptors.response.use(
  response => {
    // toLogin()
    console.log(response, '<===== api.interceptors.response')
    if (response?.data?.code != 200) { // 登录成功外的情况
      // 如果接口请求时发现 token 失效，则立马跳转到登录页
      if (response?.data?.code === 101) {
        toLogin()
      }
      Message.error(response?.data?.msg ?? '服务器繁忙，请稍后再试')
      return Promise.reject(response?.data ?? null);
    }
    return Promise.resolve(response?.data ?? {});
  },
  error => {
    console.log(error, '<===== api.interceptors - error');
    console.log(error?.response, "error.response");
    let msg = '请求失败';
    if (error?.response?.data?.code === 101) {
      console.log('????? 重置到登录页面');
      toLogin();
    }
    if (error?.response?.data?.msg) msg = error?.response?.data?.msg;
    Message.error(msg);
    return Promise.reject(error)
  }
)
export default api
